﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UCL;
using UCL.Forms;
using UCL.Data;

namespace DBKit5
{
    /// <summary>
    /// 脚本分发
    /// <remarks>1.0.0 2013-10-17 sutroon</remarks>
    /// </summary>
    public partial class frmScriptDistribute_bak : Form
    {
        AppDataHelper adh;
        public frmScriptDistribute_bak()
        {
            InitializeComponent();
        }

        private void frmScriptDistribute_Load(object sender, EventArgs e)
        {
            adh = new AppDataHelper();
            FormLoad_Group();
        }

        /// <summary>
        /// 读取分组列表
        /// </summary>
        private void FormLoad_Group()
        {
            tvGroup.Nodes.Clear();
            string xml = adh.GetCatalogTreeText("CONNECTION_GROUP");
            tvGroup.LoadXmlString(xml);
            tvGroup.ExpandAll();
        }

        /// <summary>
        /// 读取连接列表
        /// </summary>
        /// <param name="search"></param>
        private void FormLoad_Connections(string search = "")
        {
            if (search.Length == 0 && tvGroup.SelectedNode != null) search = "GroupID=" + tvGroup.SelectedNode.Name;
            if (search.Length > 0) search = " where " + search;
            DataTable dt = adh.ExecuteDataTable("select * from tconnections" + search);
            if (dt.Rows.Count == 0) return;
            if (chklbConnections.Items.Count == 0)
            {
                chklbConnections.SetDataSource(dt);
                return;
            }
            DataTable dtSource = chklbConnections.GetDataSource<DataTable>();
            if (dtSource.Select("Name='{0}'".Fmt(dt.GetValue<string>(r => { return r["Name"]; }))).Length > 0) return;
            dtSource.Merge(dt);
        }

        private void tvGroup_AfterSelect(object sender, TreeViewEventArgs e)
        {
            FormLoad_Connections();
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            if (tbSql.TextLength == 0 || chklbConnections.CheckedItems.Count == 0) return;
            IDatabaseHelper idh;
            DataRowView row;
            List<string> msg = new List<string>();
            foreach (object r in chklbConnections.CheckedItems)
            {
                row = r as DataRowView;
                idh = adh.GetDatabaseHelper(row["ProductName"].ToString(), row["HostName"].ToString(), row["LoginID"].ToString(), row["Password"].ToString(), row["Database"].ToString());
                try
                {
                    idh.ExecuteNonQuery(tbSql.Text);
                }
                catch (Exception ex)
                {
                    msg.Add(ex.Message);
                }
            }
            MessageBox.Show(msg.Count > 0 ? msg.ToString(Environment.NewLine) : "执行成功!");
        }
    }
}
